package com.example.sprintboot.service;

import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.HashMap;
import java.util.Map;

/**
 * API调用服务示例
 * 演示如何在Spring Boot后端调用其他API
 */
@Service
public class ApiService {

    private final RestTemplate restTemplate;

    // 通过构造函数注入 RestTemplate
    public ApiService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 示例1：GET 请求 - 调用外部API获取数据
     * 
     * @param apiUrl 外部API的URL
     * @return API返回的响应字符串
     */
    public String callGetApi(String apiUrl) {
        try {
            // 方式1：直接调用，返回字符串
            String response = restTemplate.getForObject(apiUrl, String.class);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return "调用API失败: " + e.getMessage();
        }
    }

    /**
     * 示例2：GET 请求 - 带查询参数
     * 
     * @param baseUrl API基础URL
     * @param param1 参数1
     * @param param2 参数2
     * @return API返回的响应
     */
    public String callGetApiWithParams(String baseUrl, String param1, String param2) {
        try {
            // 构建带查询参数的URL
            String url = UriComponentsBuilder.fromHttpUrl(baseUrl)
                    .queryParam("param1", param1)
                    .queryParam("param2", param2)
                    .toUriString();
            
            String response = restTemplate.getForObject(url, String.class);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return "调用API失败: " + e.getMessage();
        }
    }

    /**
     * 示例3：POST 请求 - 发送JSON数据
     * 
     * @param apiUrl API的URL
     * @param requestData 要发送的数据（Map格式）
     * @return API返回的响应
     */
    public String callPostApi(String apiUrl, Map<String, Object> requestData) {
        try {
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            // 创建请求实体（包含请求头和请求体）
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestData, headers);
            
            // 发送POST请求
            ResponseEntity<String> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "调用API失败: " + e.getMessage();
        }
    }

    /**
     * 示例4：POST 请求 - 发送对象数据
     * 
     * @param apiUrl API的URL
     * @param requestObject 要发送的对象
     * @return API返回的响应
     */
    public String callPostApiWithObject(String apiUrl, Object requestObject) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<Object> requestEntity = new HttpEntity<>(requestObject, headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );
            
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "调用API失败: " + e.getMessage();
        }
    }

    /**
     * 示例5：带请求头的API调用（例如需要Token认证）
     * 
     * @param apiUrl API的URL
     * @param token 认证Token
     * @return API返回的响应
     */
    public String callApiWithAuth(String apiUrl, String token) {
        try {
            // 设置请求头，包含认证Token
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + token);  // 设置Token
            
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.GET,
                    requestEntity,
                    String.class
            );
            
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "调用API失败: " + e.getMessage();
        }
    }

    /**
     * 示例6：PUT 请求 - 更新数据
     * 
     * @param apiUrl API的URL
     * @param requestData 要更新的数据
     * @return API返回的响应
     */
    public String callPutApi(String apiUrl, Map<String, Object> requestData) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestData, headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.PUT,
                    requestEntity,
                    String.class
            );
            
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "调用API失败: " + e.getMessage();
        }
    }

    /**
     * 示例7：DELETE 请求 - 删除数据
     * 
     * @param apiUrl API的URL（包含要删除的资源ID）
     * @return API返回的响应
     */
    public String callDeleteApi(String apiUrl) {
        try {
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);
            
            ResponseEntity<String> response = restTemplate.exchange(
                    apiUrl,
                    HttpMethod.DELETE,
                    requestEntity,
                    String.class
            );
            
            return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return "调用API失败: " + e.getMessage();
        }
    }

    /**
     * 示例8：调用本地API（调用自己项目的其他接口）
     * 
     * @param localUrl 本地API的URL
     * @return API返回的响应
     */
    public String callLocalApi(String localUrl) {
        try {
            // 调用本地API，例如：http://localhost:9090/article/selectAll
            String response = restTemplate.getForObject(localUrl, String.class);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return "调用本地API失败: " + e.getMessage();
        }
    }
}

